<?php
namespace EasySwoole\EasySwoole;


use App\Extend\SysExtend\Cache\Cache;
use App\Extend\SysExtend\Database\Database;
use App\Extend\SysExtend\Helper;
use App\Extend\SysExtend\Middleware\MiddlewareManager;
use App\Extend\SysExtend\Queue\QueueManager;
use App\Extend\SysExtend\Template\TpTemplate;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Template\Render;


class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
        // 注册自定义配置项
        (new \App\Extend\SysExtend\Config\Config())->load();
        // 注册中间件信息
        (new MiddlewareManager())->saveRuleToFile();

    }

    /**
     * @param EventRegister $register
     */
    public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.
        // 注册数据库连接池
        Database::registerPool();
        // 注册缓存连接池
        Cache::getInstance();
        // 注册队列
        QueueManager::getInstance()->register(Helper::config('queue.boot_queue')??[]);
        // 注册模板引擎
        TpTemplate::register();
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        // 将当前请求对象放入容器中
        Di::getInstance()->set('request',$request);
        // 执行中间件前置方法
        if(Di::getInstance()->get('middlewareManager')->handelBefore($request, $response) === false) {
            return false;
        }
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
        // 执行中间件后置方法
        Di::getInstance()->get('middlewareManager')->handelAfter($request, $response);
    }
}